package com.lidx.back.statistics.rest;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;
import com.lidx.back.statistics.commons.Constants;
import com.lidx.back.statistics.entity.ClientInfo;
import com.lidx.back.statistics.entity.FeedBack;
import com.lidx.back.statistics.entity.MaterialCategory;
import com.lidx.back.statistics.entity.MaterialPO;
import com.lidx.back.statistics.entity.SystemVersionConfig;
import com.lidx.back.statistics.rest.app.AppInitRequestCheck;
import com.lidx.back.statistics.rest.app.AppVersionCheckBody;
import com.lidx.back.statistics.rest.app.AppVersionCheckRequest;
import com.lidx.back.statistics.rest.app.AppVersionCheckResponse;
import com.lidx.back.statistics.rest.feedback.FeedbackInputCheck;
import com.lidx.back.statistics.rest.feedback.FeedbackRequest;
import com.lidx.back.statistics.rest.feedback.FeedbackResponse;
import com.lidx.back.statistics.rest.material.CategoryBean;
import com.lidx.back.statistics.rest.material.GetAllMaterialsInputCheck;
import com.lidx.back.statistics.rest.material.GetCategoriesBody;
import com.lidx.back.statistics.rest.material.GetCategoriesResponse;
import com.lidx.back.statistics.rest.material.MaterialBean;
import com.lidx.back.statistics.rest.material.MaterialCategoriesRequest;
import com.lidx.back.statistics.rest.material.MaterialRequest;
import com.lidx.back.statistics.rest.material.MaterialResponse;
import com.lidx.back.statistics.rest.material.RestMaterialBody;
import com.lidx.back.statistics.service.IAppInitService;
import com.lidx.back.statistics.service.IFeedbackService;
import com.lidx.back.statistics.service.IMaterialCategoryService;
import com.lidx.back.statistics.service.IMaterialService;
import com.lidx.back.statistics.service.ISystemVersionService;
import com.lidx.back.statistics.utils.BeanCopyUtils;
/**
 * 
 * @author chenweidong
 * 提供app端获取数据的api接口
 *
 */
@RestController
@RequestMapping(value="app")
public class RestApi {
	
	protected static final Logger LOGGER = LoggerFactory.getLogger(RestApi.class);

	@Autowired
	private IAppInitService appInitService;
	@Autowired
	private IMaterialService materialService;
	@Autowired
	private IFeedbackService feedbackService;
	@Autowired
	private IMaterialCategoryService categoryService;
	@Autowired
	private ISystemVersionService versionService;
	
	@RequestMapping(value="init",method=RequestMethod.POST,consumes="application/json")
	public RestResponse appInit(@RequestBody RestRequest restRequest){
		RestResponse restResponse = new RestResponse();
		RestResponseBody body = new RestResponseBody();
		try{
			Assert.notNull(restRequest, "请求不能为空");
			AppInitRequestCheck inputCheck = new AppInitRequestCheck();
			ClientInfo info = inputCheck.checkInput(restRequest);
			if(!appInitService.checkInfoIfExists(info)){
				LOGGER.debug("save client info.deviceid: {}",info.getDeviceId());
				appInitService.saveClientInfo(info);
			}
			restResponse.setRspMsg(Constants.RESPONSE_SECCESS);
			restResponse.setBody(body);
		}catch(java.lang.Exception e){
			e.printStackTrace();
			restResponse.setRspMsg(Constants.RESPONSE_ERROR);
			restResponse.setBody(body);
		}
		return restResponse;
	}
	
	/*@RequestMapping(value="getRecommendMaterials",method=RequestMethod.POST,consumes="application/json")
	public MaterialResponse getRecommendMaterialList(@RequestBody RecommendMaterialRequest recommendMaterialRequest){
		MaterialResponse materialResponse = new MaterialResponse();
		try{
			Assert.notNull(recommendMaterialRequest, "请求不能为空");
			GetRecommendMaterialsInputCheck inputCheck = new GetRecommendMaterialsInputCheck();
			inputCheck.checkInput(recommendMaterialRequest);
			String versionNumber = recommendMaterialRequest.getVersion().getVersionNumber();
			String versionType = recommendMaterialRequest.getVersion().getVersionType();
			String deviceId = recommendMaterialRequest.getDeviceId();
			List<MaterialPO> materialPOs = materialService.findRecommendMaterials(versionType, versionNumber, deviceId);
			materialResponse.setMaterials(materialPOs);
			materialResponse.setRspMsg(Constants.RESPONSE_SECCESS);
		}catch(Exception e){
			e.printStackTrace();
			materialResponse.setRspMsg(Constants.RESPONSE_ERROR);
			materialResponse.setMaterials(null);
		}
		return materialResponse;
	}*/
	
	@RequestMapping(value="getAllMaterials",method=RequestMethod.POST,consumes="application/json")
	public MaterialResponse getAllMaterials(@RequestBody MaterialRequest materialRequest) {
		MaterialResponse materialResponse = new MaterialResponse();
		try{
			Assert.notNull(materialRequest, "请求不能为空");
			GetAllMaterialsInputCheck inputCheck = new GetAllMaterialsInputCheck();
			inputCheck.checkInput(materialRequest);
			VersionBean versionBean = materialRequest.getVersion();
			String versionType = versionBean.getVersionType();
			String versionNumber = versionBean.getVersionNumber();
			LOGGER.debug("getAllMaterials params 手机版本{}, app版本号{}", versionType, versionNumber);
			List<MaterialPO> materialPOs = materialService.findAllMaterialList(versionType,versionNumber);
			List<MaterialBean> materialBeans = Lists.newArrayList();
			for(MaterialPO po : materialPOs){
				MaterialBean bean = new MaterialBean();
				BeanCopyUtils.copySamePropertiesTo(po, bean);
				materialBeans.add(bean);
			}
			RestMaterialBody body = new RestMaterialBody();
			body.setMaterials(materialBeans);
			materialResponse.setBody(body);
			materialResponse.setRspMsg(Constants.RESPONSE_SECCESS);
		}catch(java.lang.Exception e){
			e.printStackTrace();
			materialResponse.setRspMsg(Constants.RESPONSE_ERROR);
		}
		
		return materialResponse;
	}
	
	@RequestMapping(value="feedback",method=RequestMethod.POST,consumes="application/json")
	public FeedbackResponse sendFeedBack(@RequestBody FeedbackRequest feedbackRequest){
		FeedbackResponse feedbackResponse = new FeedbackResponse();
		RestResponseBody body = new RestResponseBody();
		try{
			Assert.notNull(feedbackRequest);
			FeedbackInputCheck inputCheck = new FeedbackInputCheck();
			FeedBack feedBack = inputCheck.checkInput(feedbackRequest);
			LOGGER.debug("save feedback begin.");
			feedbackService.saveFeedback(feedBack);
			feedbackResponse.setRspMsg(Constants.RESPONSE_SECCESS);
			feedbackResponse.setBody(body);
		}catch(java.lang.Exception e){
			e.printStackTrace();
			feedbackResponse.setRspMsg(Constants.RESPONSE_ERROR);
			feedbackResponse.setBody(body);
		}
		return feedbackResponse;
	}

	@RequestMapping(value="getMaterialCategories",method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE)
	public GetCategoriesResponse getAllCategories(@RequestBody MaterialCategoriesRequest request){
		GetCategoriesResponse response = new GetCategoriesResponse();
		GetCategoriesBody body = new GetCategoriesBody();
		try {
			Assert.notNull(request);
			String deviceId = request.getDeviceId();
			if(StringUtils.isEmpty(deviceId)){
				throw new RuntimeException("deviceId不能为空");
			}
			LOGGER.debug("get categories, deviceid is {} ",deviceId);
			List<MaterialCategory> materialCategories = categoryService.getCategories(deviceId);
			
			List<MaterialCategory> sortedMaterialCategories = Lists.newArrayList(materialCategories);
			//sortedMaterialCategories.
			
			for(MaterialCategory category : materialCategories){
				String order = category.getOrder();
				sortedMaterialCategories.set(Integer.parseInt(order)-1, category);
			}
			
			//String[] categories = new String[materialCategories.size()];
			/*for(int i = 0;i<materialCategories.size();i++){
				categories[i] = materialCategories.get(i).getCategoryName();
			}*/
			List<CategoryBean> categoryBeans =Lists.newArrayList();
			CategoryBean categoryBean;
			for(int i = 0;i < sortedMaterialCategories.size();i++){
				categoryBean = new CategoryBean();
				MaterialCategory category = sortedMaterialCategories.get(i);
				BeanCopyUtils.copySamePropertiesTo(category, categoryBean);
				categoryBeans.add(categoryBean);
			}
			body.setCategories(categoryBeans);
			response.setBody(body);
			response.setRspMsg(Constants.RESPONSE_SECCESS);
		} catch (Exception e) {
			e.printStackTrace();
			response.setRspMsg(Constants.RESPONSE_ERROR);
			response.setBody(null);
		}
		return response;
	}
	@RequestMapping(value="appVersionCheck",method=RequestMethod.POST,consumes="application/json")
	public AppVersionCheckResponse versionCheck(@RequestBody AppVersionCheckRequest request){
		AppVersionCheckResponse response = new AppVersionCheckResponse();
		AppVersionCheckBody body = new AppVersionCheckBody();
		try{
			Assert.notNull(request);
			VersionBean versionBean = request.getVersion();
			SystemVersionConfig versionConfig = versionService.getVersionConfig(versionBean);
			body.setSystemVersionConfig(versionConfig);
			response.setBody(body);
			response.setRspMsg(Constants.RESPONSE_SECCESS);
		}catch(Exception e){
			e.printStackTrace();
			response.setRspMsg(Constants.RESPONSE_ERROR);
			response.setBody(null);
		}
		return response;
	}
}
